#!/bin/sh

#
# RedPorts Tinderbox repository creation script
#
# $Id: rpmaintainrepo 243 2011-12-07 13:23:14Z decke $
#

# Requirements:
#   tinderbox (ports-mgmt/tinderbox)
#   zfs

ACTION=$1
REPOSITORY=$2
REPOSITORYMD5=`echo $2 | md5`
TMP=/tmp/rptinderbox-repos

if [ -z "$1" -o -z "$2" ]; then
    echo "Usage ${0##*/} action repository"
    echo ""
    echo "Action:"
    echo "  create         Download and create repository"
    echo "  destroy        Remove repository"
    echo "  update         Update repository to latest revision"
    echo ""
    echo "Options:"
    echo "  repository     Subversion Repository URL"
    echo ""
    exit 1
fi

if [ "${ACTION}" = "create" ]; then
    if zfs list zroot/tinderbox/${REPOSITORYMD5} >/dev/null 2>/dev/null ; then
        echo "Repository already exists"
        exit 1
    fi

    mkdir -p ${TMP}/${REPOSITORYMD5} || exit 1
    zfs create -o compression=lzjb -o setuid=off zroot/tinderbox/${REPOSITORYMD5} || exit 2
    zfs set mountpoint=${TMP}/${REPOSITORYMD5} zroot/tinderbox/${REPOSITORYMD5} || exit 2
    svn checkout ${REPOSITORY} ${TMP}/${REPOSITORYMD5}/ports || exit 3

    echo "Repository successfully created"

elif [ "${ACTION}" = "update" ]; then
    if [ ! -d "${TMP}/${REPOSITORYMD5}" ]; then
        if [ ! -d "${TMP}/${REPOSITORY}" ];  then
            echo "Repository does not exist"
            exit 1
        else
            REPOSITORYMD5="${REPOSITORY}"
        fi
    fi

    svn update ${TMP}/${REPOSITORYMD5}/ports || exit 3

    echo "Repository successfully updated"

elif [ "${ACTION}" = "destroy" ]; then
    if ! zfs list zroot/tinderbox/${REPOSITORYMD5} >/dev/null 2>/dev/null ; then
        if ! zfs list zroot/tinderbox/${REPOSITORY} >/dev/null 2>/dev/null ; then
            echo "Repository does not exist"
            exit 1
        else
            REPOSITORYMD5="${REPOSITORY}"
        fi
    fi

    zfs destroy -R zroot/tinderbox/${REPOSITORYMD5} || exit 2
    rm -rf ${TMP}/${REPOSITORYMD5} || exit 1

    echo "Repository successfully removed"
fi

exit 0
